/*
 *
 *  Copyright (C) 2010 Tal Eisenberg
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package tal.drivechain.variable.types;

import tal.drivechain.matchers.ValueMatcher;
import tal.drivechain.matchers.WildcardMatcher;
import tal.drivechain.midi.MidiUtility;
import tal.drivechain.parsing.ParsingAid;
import tal.drivechain.parsing.UnitParser;

/**
 *
 * @author Main
 */
public abstract class NumberType extends DataType {
    public NumberType(String name, Class valueClass, int typecode) {
        super(name, valueClass, typecode);
        if (!(Number.class.isAssignableFrom(valueClass))) throw new IllegalArgumentException("DataType " + getName() + " can't be a number with a value class of " + valueClass);
    }
    
    @Override
    public Object parseValue(String value) throws IllegalArgumentException {
        try {
            Number dval = parseNonNumerical(value);
            if (dval==null)
                dval = UnitParser.parse(value);
            // if the value was not a simple number a cast is used to set the right type
            if (!ParsingAid.NUMBER_PATTERN.matcher(value).matches()) return cast(dval);
            else return parseNumber(dval);
        } catch (NumberFormatException ne) {
            throw new IllegalArgumentException("Can't parse as a number: '" + value + "'");
        }

    }

    protected abstract Object parseNumber(Number value) throws IllegalArgumentException;
    
    @Override
    public ValueMatcher createValueMatcher() throws IllegalArgumentException {
        return new WildcardMatcher("tal.drivechain.wildcard.DoubleElement");
    }

    private Number parseNonNumerical(String value) {
        if (MidiUtility.MIDINOTE_PATTERN.matcher(value).matches()) {
            return new Integer(MidiUtility.stringToNoteNumber(value));
        } else if (value.endsWith("dur")) {
            String dur = value.substring(0, value.length()-3);
            return new Long(MidiUtility.parseMidiDuration(dur));
        } else if (MidiUtility.MIDIDURATION_PATTERN.matcher(value).matches()) {
            return new Long(MidiUtility.parseMidiDuration(value));
        } else return null;
    }
}
